<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebRTC Camera (Mobile)</title>
</head>
<body>
    <video id="remoteVideo" autoplay playsinline></video>

    <script>
        const remoteVideo = document.getElementById('remoteVideo');

        let peerConnection;
        const ws = new WebSocket('wss://192.168.0.120:8888'); // 替换为信令服务器的 IP 和端口

        // 初始化 RTCPeerConnection
        function createPeerConnection() {
            peerConnection = new RTCPeerConnection({
                //iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] // 使用 Google 的公共 STUN 服务器
            });

            // 处理远程视频流
            peerConnection.ontrack = (event) => {
                console.log('Received track:', event.track);
                if (event.track.kind === 'video') {
                    remoteVideo.srcObject = event.streams[0];
                    remoteVideo.play(); // 确保视频播放
                }
            };

            // 处理 ICE Candidate
            peerConnection.onicecandidate = (event) => {
                if (event.candidate) {
                    ws.send(JSON.stringify({ type: 'candidate', candidate: event.candidate }));
                }
            };
        }

        // WebSocket 消息处理
        ws.onmessage = async (message) => {
            const data = JSON.parse(message.data);
            console.log('Received data:', data);

            if (data.type === 'offer') {
                // 创建 RTCPeerConnection
                createPeerConnection();//这样才能保证在初始化RTCPeerConnection时就设置ontrack

                // 设置远程描述
                await peerConnection.setRemoteDescription(new RTCSessionDescription(data.offer));

                // 创建 Answer
                const answer = await peerConnection.createAnswer();
                await peerConnection.setLocalDescription(answer);

                // 发送 Answer 到信令服务器
                ws.send(JSON.stringify({ type: 'answer', answer: answer }));
            } else if (data.type === 'candidate') {
                // 收到 ICE Candidate，添加到连接中
                if (peerConnection) {
                    await peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
                }
            }
        };
    </script>
</body>
</html>